<template>
  <inline-Modal
    :visible="visible"
    :title="filterTitle()"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="submitLoading"
      @click="handelOk()"
      v-if="[1, 2, 4].includes(pageOperate)"
    >
      确定
    </a-button>
    <div class="wrapPage-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <!-- 新增、编辑数据 -->
        <div class="warp-container">
          <a-form-model-item
            label="名称"
            prop="name"
            :rules="{
              required: pageOperate == 4 || pageOperate == 3 ? false : true,
              message: '请输入名称',
            }"
          >
            <a-input
              v-model="form.name"
              placeholder="请输入"
              :disabled="isDisabled"
            ></a-input>
          </a-form-model-item>
          <a-row :gutter="0">
            <a-col :span="8">
              <a-form-model-item
                label="时间"
                prop="time"
                :rules="{
                  required: pageOperate == 4 || pageOperate == 3 ? false : true,
                  message: '请选择时间',
                }"
              >
                <a-date-picker
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="form.time"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :disabled="isDisabled"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="地点"
                prop="location"
                :rules="{
                  required: pageOperate == 4 || pageOperate == 3 ? false : true,
                  message: '请输入地点',
                }"
              >
                <a-input
                  v-model="form.location"
                  placeholder="请输入"
                  :disabled="isDisabled"
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="专业"
                prop="major"
                :rules="{
                  required: pageOperate == 4 || pageOperate == 3 ? false : true,
                  message: '请选择专业',
                }"
              >
                <a-select
                  v-model="form.major"
                  placeholder="请选择"
                  showSearch
                  :filter-option="filterOption"
                  :disabled="isDisabled"
                  @change="changeMajor($event)"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in majorSource"
                    :key="item.dicItemCode"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item
            label="参会人员"
            prop="participantsIds"
            :rules="{
              required: pageOperate == 4 || pageOperate == 3 ? false : true,
              message: '请选择参会人员',
            }"
          >
            <a-tree-select
              :disabled="isDisabled"
              multiple
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              treeNodeFilterProp="title"
              show-search
              allowClear
              :tree-data="participantsSource"
              placeholder="请选择"
              :replaceFields="{
                children: 'children',
                title: 'text',
                key: 'value',
                value: 'value',
              }"
              v-model="form.participantsIds"
              @change="changePeople"
            />
          </a-form-model-item>

          <a-form-model-item label="其他文件">
            <bjUploadFile
              :viewMode="isDisabled"
              :count="20"
              v-model="form.otherDocuments"
              @preview="viewFile($event)"
              @download="downloadFile($event, 2)"
              @change="handleUpLoadFile($event, 'otherDocuments')"
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>

          <a-form-model-item
            label="图纸/模型"
            prop="fileSource"
            :rules="{
              required: pageOperate == 4 || pageOperate == 3 ? false : true,
              message: '请选择图纸/模型',
            }"
          >
            <a-radio-group
              v-model="form.fileSource"
              @change="changeFileSource($event)"
              :disabled="isDisabled"
            >
              <a-radio :value="1">
                引用
              </a-radio>
              <a-radio :value="2">
                上传
              </a-radio>
            </a-radio-group>
            <div class="base-container">
              <div class="base-left">
                <a-form-model-item
                  label=" "
                  prop="type"
                  v-if="form.fileSource == 1"
                  :rules="{
                    required:
                      pageOperate == 4 || pageOperate == 3 ? false : true,
                    message: '请选择引用',
                  }"
                >
                  <a-radio-group
                    v-model="form.type"
                    @change="changeType()"
                    :disabled="isDisabled"
                  >
                    <a-radio :value="3">
                      初步设计
                    </a-radio>
                    <a-radio :value="4">
                      施工图设计
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
                <div class="tree-container">
                  <a-empty v-if="treeData.length == 0" :description="false" />
                  <a-tree
                    v-else
                    v-model="checkedKeys"
                    show-icon
                    show-line
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    :selected-keys="selectedKeys"
                    :tree-data="treeData"
                    :replaceFields="{
                      children: 'children',
                      title: 'nodeName',
                      key: 'uuid',
                    }"
                    @expand="onExpand"
                    @select="onSelect"
                  >
                    <!-- 自定义图标 -->
                    <template slot="custom" slot-scope="{ expanded }">
                      <a-icon
                        :type="expanded ? 'folder-open' : 'folder'"
                        theme="filled"
                      />
                    </template>
                    <template
                      slot="title"
                      slot-scope="{
                        nodeName,
                        id,
                        uuid,
                        unit,
                        delBtn,
                        versionMain,
                      }"
                    >
                      <div class="custom-tree-title-warp">
                        <div class="title" :title="nodeName">
                          {{ nodeName }}
                        </div>
                        <div class="operate">
                          <!-- 新增 -->
                          <icon-font
                            type="icon-xinjianwenjianjia"
                            class="add-file-button"
                            @click.stop="addFolder(id)"
                            v-if="versionMain != 1"
                          ></icon-font>
                          <!-- 编辑 -->
                          <a-icon
                            type="edit"
                            class="edit-btn"
                            @click.stop="editFolder(nodeName, uuid, unit)"
                            v-if="delBtn == 0"
                          />
                          <!-- 删除 -->
                          <a-icon
                            type="delete"
                            class="delete-btn"
                            @click.stop="deleteFolder(uuid, id)"
                            v-if="delBtn == 0"
                          />
                        </div>
                      </div>
                    </template>
                  </a-tree>
                </div>
              </div>
              <div class="base-right">
                <div class="upload-groups">
                  <template v-if="form.fileSource == 2">
                    <a-button
                      class="cu-btn-primary margin-bottom-xs"
                      icon="cloud-upload"
                      @click="uploadFolder()"
                      v-if="
                        currentTreeNode.uploadBtn &&
                          [1, 2].includes(pageOperate)
                      "
                    >
                      上传
                    </a-button>
                    <a-button
                      class="cu-btn-primary margin-bottom-xs"
                      icon="file-zip"
                      @click="handleUploadZip({}, 1)"
                      v-if="
                        currentTreeNode.zipBtn && [1, 2].includes(pageOperate)
                      "
                    >
                      导入压缩包
                    </a-button>
                    <a-button
                      class="cu-btn-primary margin-bottom-xs"
                      icon="download"
                      @click="handleDownloadZip()"
                      v-if="[3, 4].includes(pageOperate)"
                      :loading="downloadLoading"
                      :disabled="downloadLoading"
                      v-action:tzhs_table_download
                    >
                      {{ downloadLoading ? "下载中" : "下载" }}
                    </a-button>
                  </template>
                </div>
                <div class="table-file-container">
                  <!-- -->
                  <div
                    class="drag-drop-container"
                    v-if="
                      currentTreeNode.uploadBtn &&
                        [1, 2].includes(pageOperate) &&
                        form.fileSource
                    "
                  >
                    <dragDropUpload
                      :treeItem="currentTreeNode"
                      @onRefresh="tableRefresh($event)"
                    ></dragDropUpload>
                  </div>

                  <vxe-table
                    ref="xTable"
                    height="99%"
                    align="center"
                    show-overflow
                    show-header-overflow
                    :data="tableData"
                    :column-config="{ resizable: true }"
                    size="small"
                    :loading="tableLoading"
                  >
                    <vxe-table-column width="60" v-if="form.fileSource == 1">
                      <template #header>
                        <a-checkbox
                          v-model="allChecked"
                          :indeterminate="indeterminate"
                          @change="allClick($event)"
                          :disabled="isDisabled"
                        >
                        </a-checkbox>
                      </template>
                      <template #default="{ row }">
                        <a-checkbox
                          v-model="row.select"
                          @change="changeItem($event, row)"
                          :disabled="isDisabled"
                        >
                        </a-checkbox>
                      </template>
                    </vxe-table-column>
                    <vxe-column type="seq" width="80" title="序号"></vxe-column>
                    <vxe-column
                      field="fileName"
                      title="文件名称"
                      align="left"
                      min-width="300"
                    >
                      <template #default="{ row }">
                        <div class="table-file-name">
                          <div
                            class="icon"
                            :class="[getFileIconName(row.fileName)]"
                          ></div>
                          <div class="name" @click="previewFile(row)">
                            {{ row.fileName }}
                          </div>
                        </div>
                      </template>
                    </vxe-column>
                    <vxe-column field="fileCode" title="图纸编号">
                      <template #default="{ row,rowIndex }">
                        <a-input
                          v-model="row.fileCode"
                          placeholder="请输入"
                          @change="changeInput(row, rowIndex)"
                        ></a-input>
                      </template>
                    </vxe-column>
                    <vxe-column field="creator" title="上传人" width="100">
                    </vxe-column>
                    <vxe-column
                      field="createTimeStr"
                      title="上传时间"
                      width="150"
                    >
                    </vxe-column>
                    <vxe-column
                      field="operate"
                      fixed="right"
                      width="130"
                      title="操作"
                    >
                      <template #default="{ row ,rowIndex}">
                        <div class="files-icon">
                          <!-- 预览 -->
                          <a-tooltip placement="top">
                            <template slot="title">
                              预览
                            </template>
                            <a-icon type="eye" @click="previewFile(row)" />
                          </a-tooltip>
                          <!-- 下载 -->
                          <a-tooltip
                            placement="top"
                            v-action:tzhs_table_download
                            v-if="
                              form.fileSource == 1 ||
                                [3, 4].includes(pageOperate)
                            "
                          >
                            <template slot="title">
                              下载
                            </template>
                            <a-icon
                              type="download"
                              @click="downloadFile(row, 1)"
                            />
                          </a-tooltip>
                          <a-tooltip
                            placement="top"
                            v-if="
                              form.fileSource == 2 &&
                                [1, 2].includes(pageOperate)
                            "
                          >
                            <template slot="title">
                              删除
                            </template>
                            <a-icon
                              type="delete"
                              class="delete-btn"
                              @click="deleteFile(row, rowIndex)"
                            />
                          </a-tooltip>
                        </div>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </div>
            </div>
          </a-form-model-item>

          <a-form-model-item label="备注" prop="tenantCode">
            <a-textarea
              placeholder="请输入"
              :rows="4"
              v-model="form.remark"
              :disabled="isDisabled"
            />
          </a-form-model-item>
          <a-form-model-item
            label="图纸会审纪要"
            prop="jointReview"
            :rules="{
              required: false,
              message: '请选择图纸会审纪要',
            }"
          >
            <bjUploadFile
              :viewMode="isDisabled"
              :count="20"
              v-model="form.jointReview"
              @preview="viewFile($event)"
              @download="downloadFile($event, 2)"
              @change="handleUpLoadFile($event, 'jointReview')"
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>
        </div>
        <!-- 审批数据 -->
        <template v-if="pageOperate == 4">
          <a-divider />
          <div class="warp-container">
            <a-form-model-item
              label="审批结果"
              prop="operate"
              :rules="{
                required: true,
                message: '请选择审批结果',
              }"
            >
              <a-radio-group v-model="form.operate">
                <a-radio :value="2">
                  通过
                </a-radio>
                <a-radio :value="3">
                  驳回
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="审批意见" prop="reason">
              <a-textarea
                placeholder="请输入"
                :rows="4"
                v-model="form.reason"
              />
            </a-form-model-item>
          </div>
        </template>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>

    <!-- 上传弹窗 -->
    <uploadModal
      :visible.sync="uploadModal.visible"
      :operate="uploadModal.operate"
      :treeItem="currentTreeNode"
      :parameter="uploadModal.row"
      @onRefresh="tableRefresh($event)"
    ></uploadModal>

    <!-- 新增、编辑弹窗 -->
    <addModal
      :visible.sync="addModal.visible"
      :operate="addModal.operate"
      :pid="addModal.pid"
      :nodeName="addModal.nodeName"
      @onRefresh="treeRefresh($event)"
    ></addModal>
    <!-- 上传压缩包 -->
    <uploadZipModal
      :visible.sync="uploadZipModal.visible"
      :treeItem="currentTreeNode"
      @change="zipModalChange($event)"
      :accept="['dwg', 'dxf']"
    ></uploadZipModal>
  </inline-Modal>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import {
  getToken,
  downloadDfs,
  downLoadBatchFileByArraybuffer,
} from "@/utils/TopVUI";
import {
  flatTreeData,
  addAttributeByKey,
  getNodeByKey,
  getFileIconName,
} from "@/utils/util.js";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});

//普通附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
//交底文件上传
import uploadModal from "./uploadModal";
//文件夹新增
import addModal from "@/pages/customPage/design/drawingManage/components/addModal";
//拖拽上传
import dragDropUpload from "@/pages/customPage/design/drawingManage/components/dragDropUpload";

import { getDicItemByCode, getAllProListByQX } from "@/api/common.js";
//上传压缩包
import uploadZipModal from "../designBriefing/uploadZipModal.vue";
import {
  saveDrawingReview,
  detailDrawingReview,
  exportZip67,
  approveDrawingReview,
  participantsList,
} from "@/api/design";
export default {
  provide() {
    return {
      moduleSource: () => this.pageModule,
    };
  },
  components: {
    IconFont,
    bjUploadFile,
    previewModal,
    uploadModal,
    addModal,
    uploadZipModal,
    dragDropUpload,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //1新增 2编辑 3查看 4审批
    pageOperate: {
      type: [String, Number],
      default: 1,
    },
  },
  data() {
    return {
      //压缩包弹窗
      uploadZipModal: {
        visible: false,
        fileList: [],
        treeData: [],
      },
      pageModule: 7,
      isDisabled: true,
      //项目名称
      projectSoucre: [],
      //专业
      majorSource: [],
      //参会人员
      participantsSource: [],
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //图纸管理
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      currentTreeNode: {},
      //表单
      submitLoading: false,
      form: {
        uuid: "",
        //名称
        name: "",
        //时间
        time: "",
        //地点
        location: "",
        //专业
        major: undefined,
        //参会人员
        participantsIds: [],
        participantsNames: [],
        //图纸/模型
        fileSource: 1,
        //引用
        type: 3,
        //引用文件
        quoteFiles: "",
        //图纸会审纪要
        jointReview: [],
        //其他文件
        otherDocuments: [],
        //备注
        remark: "",
        //审批结果
        operate: "",
        //审批意见
        reason: "",
      },
      rules: {},
      //表格
      tableData: [],
      tableLoading: false,
      pager: {
        page: 1,
        pageSize: 9999,
        total: 0,
      },
      //复选框
      allChecked: false,
      indeterminate: false,
      checkRowKeys: [],
      //上传
      uploadModal: {
        visible: false,
        operate: 1,
        row: {},
      },
      //新增编辑
      addModal: {
        visible: false,
        operate: 1,
        pid: "",
        nodeName: "",
      },
      //目录
      contentsAddIds: [],
      contentsDeleteIds: [],
      //文件
      fileAddIds: [],
      fileDeleteIds: [],
      //
      downloadLoading: false,
      //图纸编号
      fileCodeLs: [],
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getFileIconName,
    //打开导入压缩包弹窗
    handleUploadZip() {
      this.uploadZipModal.visible = true;
    },

    //监听压缩包弹窗
    zipModalChange(ev) {
      let { currentTreeNode } = this;
      let { fileList, treeData, addClassifyIdLs, addFileIdLs, fileInfo } = ev;
      this.uploadZipModal.fileList = fileList;
      this.uploadZipModal.treeData = treeData;
      this.uploadZipModal.addClassifyIdLs = addClassifyIdLs;
      this.uploadZipModal.fileInfo = fileInfo;
      this.uploadZipModal.addFileIdLs = addFileIdLs;
      let itemNode = getNodeByKey(
        currentTreeNode.uuid,
        "uuid",
        this.treeData,
        "children"
      );
      let zipFolderData = this.getFolderData(treeData);
      if (itemNode?.children) {
        itemNode.children.push(...zipFolderData);
      } else {
        itemNode.children = zipFolderData;
      }
      this.fileAddIds.push(...addFileIdLs);
      this.contentsAddIds.push(...addClassifyIdLs);
      this.getUploadTreeData();
    },

    //过滤出所有文件夹数据
    getFolderData(data) {
      try {
        filterData(data);
        function filterData(source = []) {
          source.forEach((item) => {
            if (item.type === "folder") {
              if (item.children && item.children.length) {
                item.children = item.children.filter(
                  (v) => v.type === "folder"
                );
                filterData(item.children);
              }
            }
          });
        }
        throw data;
      } catch (data) {
        return data;
      }
    },

    async getData() {
      await this.getPeopleData();
      await this.getTypeData();
      if (this.pageOperate != 1) {
        this.getDetail();
      }
    },

    //选择人员
    changePeople(value, label) {
      this.form.participantsNames = label;
    },

    changeInput(row, index) {
      this.fileCodeLs.push(row);
      this.fileCodeLs = this.uniqueBy(this.fileCodeLs, "uuid");
    },

    //json数组去重
    uniqueBy(arr, key) {
      const unique = {};
      return arr.filter((item) => {
        if (!unique[item[key]]) {
          unique[item[key]] = true;
          return true;
        }
        return false;
      });
    },

    //下载压缩包
    handleDownloadZip() {
      let { id, nodeName } = this.currentTreeNode;
      let { uuid } = this.form;
      this.downloadLoading = true;
      exportZip67({ uuid, classifyId: id, type: this.pageModule })
        .then((data) => {
          downLoadBatchFileByArraybuffer(data, nodeName);
        })
        .catch((_) => {})
        .finally((_) => {
          this.downloadLoading = false;
        });
    },

    //新建文件夹
    addFolder(id) {
      this.addModal.pid = id;
      this.addModal.nodeName = "";
      this.addModal.operate = 1;
      this.addModal.visible = true;
    },

    //编辑文件夹
    editFolder(nodeName, uuid, unit) {
      this.addModal.operate = 2;
      this.addModal.pid = uuid;
      this.addModal.nodeName = nodeName;
      this.addModal.visible = true;
    },

    //删除文件夹
    deleteFolder(uid = "", id) {
      let { uuid } = this.currentTreeNode;
      this.contentsDeleteIds.push(id);
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            that
              .$post(`/probusiness/bimCadClassify/deleteData?uuid=${uid}`)
              .then((res) => {
                let { statusCode, message } = res;
                if (statusCode == 200) {
                  that.$message.success("删除成功！");
                  if (uuid == uid) {
                    that.currentTreeNode = {};
                    that.tableData = [];
                  }
                  that.getUploadTreeData();
                } else {
                  that.$message.error(message ?? "删除失败，请稍后重试！");
                }
                resolve();
              })
              .catch((_) => {
                reject();
              })
              .finally((_) => {});
          }).catch(() => console.log("Oops errors!"));
        },
      });
    },

    //左侧树刷新
    treeRefresh(id) {
      this.contentsAddIds.push(id);
      this.getUploadTreeData();
    },

    //文件删除
    deleteFile(row, index) {
      this.fileDeleteIds.push(row.uuid);
      this.tableData.splice(index, 1);
    },

    //交底文件上传
    uploadFolder() {
      this.uploadModal.operate = 1;
      this.uploadModal.row = {};
      this.uploadModal.visible = true;
    },

    //右侧表格刷新
    tableRefresh(uuid) {
      this.fileAddIds.push(uuid);
      this.getUploadTreeData();
    },
    //选择专业
    changeMajor() {
      let { form } = this;
      //引用
      if (form.fileSource == 1) {
        this.treeData = [];
        this.tableData = [];
        this.currentTreeNode = {};
        this.checkRowKeys = [];
        this.indeterminate = false;
        this.allChecked = false;
        this.fileCodeLs = [];
        this.getDrawingTreeData();
      }
    },
    //交底文件类型
    changeFileSource() {
      let { form } = this;
      this.treeData = [];
      this.tableData = [];
      this.currentTreeNode = {};
      this.checkRowKeys = [];
      this.indeterminate = false;
      this.allChecked = false;
      this.fileCodeLs = [];
      //引用
      if (form.fileSource == 1) {
        this.getDrawingTreeData();
      }
      //上传
      if (form.fileSource == 2) {
        this.getUploadTreeData();
      }
    },

    //交底文件预览
    previewFile(row) {
      let { previewWay, uuid, fileInfo, unit, bhDataSetId } = row;
      let { fileName, url } = fileInfo;
      let domain = location.origin;
      switch (previewWay) {
        //cad预览
        case "cad":
          window.open(
            `${domain}/#/blackHole/previewCad?uuid=${uuid}&fileName=${fileName}&unit=${unit}`
          );
          return;
        // 模型预览
        case "model":
          bhDataSetId &&
            window.open(
              `${domain}/#/blackHole/viewDataSetSingleSimple?dataSetId=${bhDataSetId}&name=${fileName}`
            );
          return;
        // 普通文件预览
        case "kkview":
          this.viewFile(fileInfo);
          return;
        default:
          break;
      }
    },

    //引用
    changeType() {
      this.checkRowKeys = [];
      this.fileCodeLs = [];
      this.tableData = [];
      this.allChecked = false;
      this.indeterminate = false;
      this.currentTreeNode = {};
      this.getDrawingTreeData();
    },

    //详情
    getDetail() {
      return new Promise((resolve, reject) => {
        let { uuid } = this.parameter;
        detailDrawingReview({ uuid })
          .then((res) => {
            let { data } = res;
            this.form = {
              uuid: data?.uuid,
              //名称
              name: data?.name,
              //时间
              time: data?.time,
              //地点
              location: data?.location,
              //专业
              major: data?.major,
              //图纸/模型
              fileSource: data?.fileSource,
              //引用
              type: data?.type,
              //引用文件
              quoteFiles: data?.quoteFiles ?? "",
              //图纸会审纪要
              jointReview: JSON.parse(data?.jointReview ?? "[]"),
              //其他文件
              otherDocuments: JSON.parse(data?.otherDocuments ?? "[]"),
              //备注
              remark: data?.remark,
              //参会人员
              participantsIds: data?.participantsIds.split(",") ?? [],
              participantsNames: data?.participantsNames.split(",") ?? [],
            };
            //引用
            this.checkRowKeys = this.form.quoteFiles.split(",");
            //图纸模型
            if (this.form.fileSource == 1) {
              this.getDrawingTreeData();
            }
            if (this.form.fileSource == 2) {
              this.getUploadTreeData();
            }
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },

    //查询所有项目
    getProjectData() {
      return new Promise((resolve, reject) => {
        getAllProListByQX()
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询专业
    getTypeData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "major" })
          .then((res) => {
            let { data } = res;
            this.majorSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.majorSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询参会人员
    getPeopleData() {
      return new Promise((resolve, reject) => {
        participantsList({})
          .then((res) => {
            let { data } = res;
            this.participantsSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.participantsSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询上传树形数据
    getUploadTreeData() {
      let { uuid = "", fileSource } = this.form;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/drawingReview/getTreeByProCodeInner`,
            {
              uuid,
              type: this.pageModule,
              addClassifyIdLs: this.contentsAddIds,
              deleteClassifyIdLs: this.contentsDeleteIds,
              fileSource,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            let source = data ?? [];
            let flatData = flatTreeData(source, "children");
            this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "children"
            );
            this.treeData = filterData ?? [];
            //
            this.currentTreeNode = this.treeData?.[0] ?? {};
            this.selectedKeys = [this.currentTreeNode.uuid];
            this.handleUploadTable();
            resolve();
          })
          .catch((_) => {
            this.currentTreeNode = {};
            this.expandedKeys = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询上传表格
    handleUploadTable() {
      let { id } = this.currentTreeNode;
      let { uuid = "" } = this.form;
      if (!id) {
        return;
      }
      this.tableLoading = true;
      axios
        .post(
          `/probusiness/bimCadFile/getListByForeignKey`,
          {
            classifyId: id,
            type: this.pageModule,
            uuid,
            addFileIdLs: this.fileAddIds,
            deleteFileIdLs: this.fileDeleteIds,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.tableData = data ?? [];
          this.tableData.forEach((item) => {
            this.fileCodeLs.forEach((v) => {
              if (item.uuid == v.uuid) {
                item.fileCode = v.fileCode;
              }
            });
          });
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },

    //查询设计树形数据
    getDrawingTreeData() {
      let { major, type } = this.form;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/drawingReview/getYYTreeByProCode`,
            {
              type,
              major,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            let source = data ?? [];
            let flatData = flatTreeData(source, "children");
            this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "children"
            );
            this.treeData = filterData ?? [];
            //
            this.currentTreeNode = this.treeData?.[0] ?? {};
            this.selectedKeys = [this.currentTreeNode.uuid];
            this.handletDrawingTable();
            resolve();
          })
          .catch((_) => {
            this.currentTreeNode = {};
            this.expandedKeys = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询设计表格
    handletDrawingTable() {
      let { id } = this.currentTreeNode;
      let { type } = this.form;
      if (!id) {
        return;
      }
      this.tableLoading = true;
      let { page, pageSize } = this.pager;
      axios
        .post(
          `/probusiness/bimCadFile/getPageSet?pageNo=${page}&pageSize=${pageSize}`,
          {
            classifyId: id,
            fileName: "",
            creator: "",
            startTime: "",
            endTime: "",
            type,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          let source = data?.rows ?? [];
          //过滤不是cad的文件
          source.forEach((v) => {
            let lastIdx = v.fileName.lastIndexOf(".");
            let fileType = "." + v.fileName.substring(lastIdx + 1);
            this.$set(v, "bhFileType", fileType);
          });
          this.tableData = source.filter((v) =>
            [".dwg", ".dxf"].includes(v.bhFileType)
          );

          this.pager.total = data?.totalCount ?? 0;
          //
          this.tableData.forEach((item) => {
            this.fileCodeLs.forEach((v) => {
              if (item.uuid == v.uuid) {
                item.fileCode = v.fileCode;
              }
            });
          });
          //
          this.tableData.forEach((item) => {
            if (this.checkRowKeys.includes(item.uuid)) {
              this.$set(item, "select", true);
            } else {
              this.$set(item, "select", false);
            }
          });
          try {
            this.tableData.forEach((v) => {
              if (v.select) {
                throw v;
              }
            });
            this.indeterminate = false;
          } catch (error) {
            this.indeterminate = true;
          }
          const ids = this.tableData
            .filter((item) => item.select)
            .map((v) => v.uuid);
          if (ids.length == this.tableData.length) {
            this.indeterminate = false;
          }
          if (this.tableData.length > 0) {
            this.allChecked = this.tableData.every((v) => v.select);
          } else {
            this.allChecked = false;
          }
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
          reject();
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },

    //下载
    downloadFile(row, type) {
      //引用文件
      if (type == 1) {
        let { fileInfo } = row;
        // 创建一个<a>元素
        const link = document.createElement("a");
        // 设置文件的URL
        link.href = fileInfo.url;
        // 设置下载后的文件名
        link.download = fileInfo.fileName;
        // 将<a>元素添加到页面中
        document.body.appendChild(link);
        // 模拟点击<a>元素
        link.click();
        // 移除<a>元素
        document.body.removeChild(link);
      }
      //图纸会审纪要、其他文件
      else {
        let { url } = row;
        downloadDfs(url);
      }
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //上传附件
    handleUpLoadFile({ file, index }, domain) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[domain][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form[domain][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form[domain][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form[domain][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[domain][index], "loading", false);
        });
    },

    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
      let { form } = this;
      //引用
      if (form.fileSource == 1) {
        this.handletDrawingTable();
      }
      //上传
      if (form.fileSource == 2) {
        this.handleUploadTable();
      }
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //全选
    allClick() {
      this.indeterminate = false;
      if (this.allChecked) {
        this.tableData.forEach((v) => {
          this.$set(v, "select", true);
        });
        this.checkRowKeys = this.tableData.map((v) => v.uuid);
      } else {
        this.tableData.forEach((v) => {
          this.$set(v, "select", false);
        });
        this.checkRowKeys = [];
      }
    },

    //单选
    changeItem(event, row) {
      let { checked } = event.target;
      let { uuid } = row;
      if (checked) {
        this.checkRowKeys.push(uuid);
        this.checkRowKeys = Array.from(new Set(this.checkRowKeys));
      } else {
        this.checkRowKeys = this.checkRowKeys.filter((v) => v != uuid);
      }
      this.allChecked = this.tableData.every((v) => v.select);
      this.indeterminate =
        !!this.checkRowKeys.length &&
        this.checkRowKeys.length < this.tableData.length;
    },

    //表单提交
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { pageOperate } = this;
          //审批
          if (pageOperate == 4) {
            this.approveFormData();
          }
          //新增、编辑
          else {
            this.saveFormData();
          }
        }
      });
    },

    //新增、编辑
    saveFormData() {
      let {
        form,
        checkRowKeys,
        contentsAddIds = [],
        contentsDeleteIds = [],
        fileAddIds = [],
        fileDeleteIds = [],
        fileCodeLs = [],
      } = this;
      //图纸会审纪要
      const files_1 = form.jointReview.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );
      //其他文件
      const files_2 = form.otherDocuments.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );

      let formJson = {};
      formJson = {
        //名称
        name: form.name,
        //时间
        time: form.time,
        //地点
        location: form.location,
        //专业
        major: form.major,
        //图纸/模型
        fileSource: form.fileSource,
        //图纸会审纪要
        jointReview: JSON.stringify(files_1),
        //其他文件
        otherDocuments: JSON.stringify(files_2),
        //备注
        remark: form.remark,
        //参会人员
        participantsIds: form.participantsIds.toString(),
        participantsNames: form.participantsNames.toString(),
        //图纸编号
        fileCodeLs: [],
      };
      //图纸编号
      fileCodeLs.forEach((v) => {
        formJson.fileCodeLs.push({
          id: v.uuid,
          code: v.fileCode,
        });
      });

      //引用文件
      if (form.fileSource == 1) {
        formJson.type = form.type;
        formJson.quoteFiles = checkRowKeys.toString();
      }
      //上传文件
      if (form.fileSource == 2) {
        formJson.addClassifyIdLs = contentsAddIds;
        formJson.deleteClassifyIdLs = contentsDeleteIds;
        formJson.addFileIdLs = fileAddIds;
        formJson.deleteFileIdLs = fileDeleteIds;
      }
      //编辑
      if (form.uuid) {
        formJson.uuid = form.uuid;
      }
      this.submitLoading = true;
      saveDrawingReview(formJson)
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.handelCancel();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "操作失败");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },
    //审批
    approveFormData() {
      let { form } = this;
      let formJson = {
        uuid: form.uuid,
        operate: form.operate,
        reason: form.reason,
      };
      this.submitLoading = true;
      approveDrawingReview(formJson)
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("审批成功", 1.5);
            this.handelCancel();
          } else {
            this.$message.error(res?.message ?? "审批失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "审批失败");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    handelCancel() {
      this.$parent.getTableData();
      this.$emit("update:visible", false);
    },

    filterTitle() {
      let { pageOperate } = this;
      switch (pageOperate) {
        case 1:
          this.isDisabled = false;
          return "新增";
        case 2:
          this.isDisabled = false;
          return "编辑";
        case 3:
          this.isDisabled = true;
          return "查看";
        case 4:
          this.isDisabled = true;
          return "审批";
        default:
          break;
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  /deep/.main {
    // padding-right: 110px;
  }
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 120px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
  /deep/.bj-upload-file {
    .choosed-file-warp {
      width: 100%;
    }
  }
  .add-btn {
    position: absolute;
    top: 10px;
    right: 90px;
  }
  .wrapPage-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .warp-container {
      padding-right: 110px;
    }
    .base-container {
      height: 562px;
      overflow: hidden;
      display: flex;
      .base-left {
        width: 300px;
        flex-shrink: 0;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #d4d7d8;
        margin-right: 10px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        /deep/.ant-form-item {
          .ant-form-item-label {
            width: 56px;
          }
        }
        .tree-container {
          flex: 1;
          overflow: auto;
          overflow-x: hidden;
          position: relative;
          padding: 0 10px 0 10px;
          /deep/.ant-tree {
            .ant-tree-node-content-wrapper {
              &:hover {
                .operate {
                  .anticon {
                    display: inline-block !important;
                  }
                }
              }
            }
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                position: relative;
                width: calc(100% - 25px);
                padding: 0;
                .ant-tree-iconEle {
                  color: #ffca28;
                  font-size: 16px;
                }
                .ant-tree-title {
                  overflow: hidden;
                  display: inline-block;
                  width: calc(100% - 26px);
                  .custom-tree-title-warp {
                    display: flex;
                    width: 100%;
                    .title {
                      flex: 1;
                      overflow: hidden;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    }
                    .operate {
                      flex-shrink: 0;
                      margin-left: 8px;
                      color: #8c8c8c;
                      width: 59px;
                      .anticon {
                        display: none;
                      }
                      .add-file-button {
                        font-size: 15px;
                      }
                      .edit-btn {
                        margin: 0 8px;
                      }
                    }
                  }
                }
              }
            }
          }
          .ant-empty {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
      .base-right {
        width: calc(100% - 310px);
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        .upload-groups {
          height: 48px;
          flex-shrink: 0;
        }
        .table-file-container {
          flex: 1;
          position: relative;
          .files-icon {
            .anticon {
              cursor: pointer;
              font-size: 18px;
              color: #1677ff;
              margin-right: 16px;
              &:last-of-type {
                margin-right: 0;
              }
            }
            .anticon-download {
              color: #239b53;
            }
            .anticon-delete {
              color: #e43d3d;
            }
          }
          .drag-drop-container {
            z-index: 22;
            position: absolute;
            left: 60px;
            height: 100%;
            width: 44%;
          }
        }
        .table-file-pager {
          flex-shrink: 0;
        }
      }
    }
  }
}
</style>
